<?php

namespace app\store\model;

use app\common\model\Courses as CoursesModel;
use app\store\service\Courses as CoursesService;

/**
 * 课程模型
 * Class Courses
 * @package app\store\model
 */
class Courses extends CoursesModel
{

    protected  $dateArr = ['begin_apply_time','end_apply_time','begin_attend_time','end_attend_time','begin_apply_time_1',
        'end_apply_time_1', 'begin_apply_time_2','end_apply_time_2','begin_apply_time_3','end_apply_time_3'
    ];
    /**
     * 添加课程
     * @param array $data
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function add(array $data)
    {
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传课程图片';
            return false;
        }
        $data['content'] = $data['content'] ?? '';
        $data['wxapp_id'] = $data['wxapp_id'] = self::$wxapp_id;
        foreach ($data as $key=> &$_d){
            if (in_array($key,$this->dateArr)){
                $data[$key] = strtotime($_d);
            }
        }
        // 开启事务
        $this->startTrans();
        try {
            // 添加课程
            $this->allowField(true)->save($data);
            // 课程图片
            $this->addCoursesImages($data['images']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 添加课程图片
     * @param $images
     * @return int
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    private function addCoursesImages($images)
    {
        $this->image()->delete();
        $data = array_map(function ($image_id) {
            return [
                'image_id' => $image_id,
                'wxapp_id' => self::$wxapp_id
            ];
        }, $images);
        return $this->image()->saveAll($data);
    }

    /**
     * 编辑课程
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        if (!isset($data['images']) || empty($data['images'])) {
            $this->error = '请上传课程图片';
            return false;
        }
        $data['spec_type'] = isset($data['spec_type']) ? $data['spec_type'] : $this['spec_type'];
        $data['content'] = isset($data['content']) ? $data['content'] : '';
        $data['wxapp_id'] = $data['wxapp_id'] = self::$wxapp_id;
        foreach ($data as $key=> &$_d){
            if (in_array($key,$this->dateArr)){
                $data[$key] = strtotime($_d);
            }
        }
        return $this->transaction(function () use ($data) {
            // 保存课程
            $this->allowField(true)->save($data);
            // 课程规格
//            $this->addCoursesSpec($data, true);
            // 课程图片
            $this->addCoursesImages($data['images']);
            return true;
        });
    }

    /**
     * 添加课程规格
     * @param $data
     * @param $isUpdate
     * @throws \Exception
     */
//    private function addCoursesSpec($data, $isUpdate = false)
//    {
//        // 更新模式: 先删除所有规格
//        $model = new CoursesSku;
//        $isUpdate && $model->removeAll($this['Courses_id']);
//        // 添加规格数据
//        if ($data['spec_type'] == '10') {
//            // 单规格
//            $this->sku()->save($data['sku']);
//        } else if ($data['spec_type'] == '20') {
//            // 添加课程与规格关系记录
//            $model->addCoursesSpecRel($this['Courses_id'], $data['spec_many']['spec_attr']);
//            // 添加课程sku
//            $model->addSkuList($this['Courses_id'], $data['spec_many']['spec_list']);
//        }
//    }

    /**
     * 修改课程状态
     * @param $state
     * @return false|int
     */
    public function setStatus($state)
    {
        return $this->allowField(true)->save(['courses_status' => $state ? 10 : 20]) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        if (!CoursesService::checkIsAllowDelete($this['Courses_id'])) {
            $this->error = '当前课程正在参与其他活动，不允许删除';
            return false;
        }
        return $this->allowField(true)->save(['is_delete' => 1]);
    }

    /**
     * 获取当前课程总数
     * @param array $where
     * @return int|string
     * @throws \think\Exception
     */
    public function getCoursesTotal($where = [])
    {
        return $this->where('is_delete', '=', 0)->where($where)->count();
    }

}
